package com.test.template.publish.config.fac;

import com.test.template.publish.config.ApiConfig;
import com.test.template.publish.config.manager.VelocityConfigManager;

import java.util.concurrent.ConcurrentHashMap;

public class ApiConfigFactory implements VelocityTemplateConfigFactory<ApiConfig> {

    ConcurrentHashMap<String, ApiConfig> configHashMap = new ConcurrentHashMap<>();


    // 私有静态变量保存唯一实例
    private static volatile ApiConfigFactory instance = null;

    // 私有构造函数防止实例化
    private ApiConfigFactory() {
    }

    // 公共静态方法提供全局访问点
    public static ApiConfigFactory getInstance() {
        if (instance == null) {
            synchronized (ApiConfigFactory.class) {
                if (instance == null) {
                    instance = new ApiConfigFactory();
                    init();
                }
            }
        }
        return instance;
    }

    @Override
    public void addConfig(String key, ApiConfig apiConfig) {
        configHashMap.put(key, apiConfig);
    }

    @Override
    public ApiConfig getConfig(String key) {
        return configHashMap.get(key);
    }

    @Override
    public void addConfig(VelocityConfigManager manager) {
        ApiConfig config = buildBasicConfig(manager.getTableName(), manager.getControllerPrefix());
        getInstance().addConfig(manager.getTableName(), config);
    }

    /**
     * description 初始化函数，后续修改为配置文件读取方式执行
     *
     * @author zken
     * @CreateDate 2024/12/6 20:46:59
     */
    private static void init() {
        ApiConfig contributeConfig = buildBasicConfig("contribute", "/content/contribute");
        getInstance().addConfig("contribute", contributeConfig);
    }

    /**
     * 创建基本的配置
     *
     * @param tableName
     * @param prefix
     * @return
     */
    public static ApiConfig buildBasicConfig(String tableName, String prefix) {
        ApiConfig config = new ApiConfig();
        config.setTableName(tableName);
        config.setPrefix(prefix); // controller的prefix前缀
        config.innerGenerate();
        return config;
    }
}
